﻿using iTool.ClusterComponent;
using iTool.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace iTool.Dashboard.EmbeddedAssets
{
    public static class ServiceCollectionExtensions
    {

        public static IApplicationBuilder UseDashboard(this IApplicationBuilder app, string basePath = null)
        {
            if (string.IsNullOrEmpty(basePath) || basePath == "/")
            {
                app.UseMiddleware<DashboardMiddleware>();
            }
            else
            {
                basePath = basePath.StartsWith("/") ? basePath : $"/{basePath}";
                app.Map(basePath, a => a.UseMiddleware<DashboardMiddleware>());
            }

            return app;
        }

        public static IApplicationBuilder UseIframeDashboard(this IApplicationBuilder app, string basePath = null)
        {
            if (string.IsNullOrEmpty(basePath) || basePath == "/")
            {
                app.UseMiddleware<IframeDashboardMiddleware>();
            }
            else
            {
                basePath = basePath.StartsWith("/") ? basePath : $"/{basePath}";
                app.Map(basePath, a => a.UseMiddleware<IframeDashboardMiddleware>());
            }

            return app;
        }


        public static async Task<iToolClusterHostServer> BuildAndStartAsync(this iToolHostBuilder builder, IServiceCollection services)
        {
            var server = await builder.BuildAndStartAsync();
            services.AddSingleton<IAssetProvider, EmbeddedAssetProvider>();
            services.AddSingleton<IClusterService>(server);
            iBox.GetServiceCollection("IDashboardService", services);
            return server;
        }

        public static async Task<iToolClusterHostClient> BuildAndConnectAsync(this iToolClientBuilder builder, IServiceCollection services)
        {
            var server = await builder.BuildAndConnectAsync();
            services.AddSingleton<IAssetProvider, EmbeddedAssetProvider>();
            services.AddSingleton<IClusterService>(server);
            iBox.GetServiceCollection("IDashboardService", services);
            return server;
        }
    }
}
